package com.karaoke.list.config;

import java.util.Enumeration;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.portlet.ConfigurationAction;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portlet.PortletPreferencesFactoryUtil;

public class ConfigAction implements ConfigurationAction {

	@Override
	public void processAction(PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
			throws Exception {
		if (!Constants.UPDATE.equals(ParamUtil.getString(actionRequest, Constants.CMD))) { return; }
		PortletPreferences preferences = parsePreferences(actionRequest);
		preferences.store();
		SessionMessages.add(actionRequest, portletConfig.getPortletName() + ".doConfigure");
	}

	@Override
	public String render(PortletConfig portletConfig, RenderRequest renderRequest, RenderResponse renderResponse) throws Exception {
		return "/jsps/conf.jsp";
	}
	
	public static PortletPreferences getPreferences(PortletRequest request) throws PortalException, SystemException {
		PortletPreferences preferences = null;
		String portletResource = ParamUtil.getString(request, "portletResource");
		if (Validator.isNotNull(portletResource)) {
			preferences = PortletPreferencesFactoryUtil.getPortletSetup(request, portletResource);
		} else {
			preferences = request.getPreferences();
		}
		return preferences;
	}
	
	public static PortletPreferences parsePreferences(ActionRequest request) throws PortalException, SystemException, ReadOnlyException {
		PortletPreferences preferences = getPreferences(request);
		Enumeration<String> parameterNames = request.getParameterNames();
		String parameterName, value;
		while (parameterNames.hasMoreElements()) {
			parameterName = parameterNames.nextElement();
			if (parameterName.startsWith(StringPool.OPEN_BRACKET) && parameterName.endsWith(StringPool.CLOSE_BRACKET)) {
				value = ParamUtil.getString(request, parameterName, StringPool.BLANK);
				if (value.length() > 0) {
					parameterName = parameterName.substring(1, parameterName.length() - 1);
					preferences.setValue(parameterName, value);
				}
			}
		}
		return preferences;
	}

}
